 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=28 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:34 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Implementing hashCode
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='hashCode,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Implementing hashCode</div>

<div class='main-body'>
 
<br>Implementing <tt><a href="http://java.sun.com/javase/6/docs/api/java/lang/Object.html#hashCode()">hashCode</a></tt> :
<ul>
<li>if a class overrides <a href="TopicAction1deb-2.html"><tt>equals</tt></a>, it must override <tt>hashCode</tt></li>
<li>when they are both overridden, <tt>equals</tt> and <tt>hashCode</tt> must use the same set of fields</li>
<li>if two objects are equal, then their <tt>hashCode</tt> values must be equal as well</li>
<li>if the object is <a href="TopicActiond838-2.html">immutable</a>, then <tt>hashCode</tt> is a candidate for caching and 
<a href="TopicAction88f9-2.html">lazy initialization</a></li>
</ul>
It is a popular misconception that <tt>hashCode</tt> provides a unique
identifier for an object. It does not.
<p><b>Example 1</b>
<p>The following utility class allows simple construction of an effective
<tt>hashCode</tt>
method. It is based on the recommendations of <i><a href="http://www.amazon.com/exec/obidos/ASIN/0201310058/ref=nosim/javapractices-20">Effective
Java</a></i>, by Joshua Bloch.
<br>
<PRE>

<span class='keyword'>import</span> java.lang.reflect.Array;

<span class='comment'>/**
* Collected methods which allow easy implementation of &lt;code&gt;hashCode&lt;/code&gt;.
*
* Example use case:
* &lt;pre&gt;
*  public int hashCode(){
*    int result = HashCodeUtil.SEED;
*    //collect the contributions of various fields
*    result = HashCodeUtil.hash(result, fPrimitive);
*    result = HashCodeUtil.hash(result, fObject);
*    result = HashCodeUtil.hash(result, fArray);
*    return result;
*  }
* &lt;/pre&gt;
*/</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> HashCodeUtil {

  <span class='comment'>/**
  * An initial value for a &lt;code&gt;hashCode&lt;/code&gt;, to which is added contributions
  * from fields. Using a non-zero value decreases collisons of &lt;code&gt;hashCode&lt;/code&gt;
  * values.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>final</span> <span class='keyword'>int</span> SEED = <span class='literal'>23</span>;

  <span class='comment'>/**
  * booleans.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>int</span> hash( <span class='keyword'>int</span> aSeed, <span class='keyword'>boolean</span> aBoolean ) {
    System.out.println(<span class='literal'>"boolean..."</span>);
    <span class='keyword'>return</span> firstTerm( aSeed ) + ( aBoolean ? <span class='literal'>1</span> : <span class='literal'>0</span> );
  }

  <span class='comment'>/**
  * chars.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>int</span> hash( <span class='keyword'>int</span> aSeed, <span class='keyword'>char</span> aChar ) {
    System.out.println(<span class='literal'>"char..."</span>);
    <span class='keyword'>return</span> firstTerm( aSeed ) + (<span class='keyword'>int</span>)aChar;
  }

  <span class='comment'>/**
  * ints.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>int</span> hash( <span class='keyword'>int</span> aSeed , <span class='keyword'>int</span> aInt ) {
    <span class='comment'>/*
    * Implementation Note
    * Note that byte and short are handled by this method, through
    * implicit conversion.
    */</span>
    System.out.println(<span class='literal'>"int..."</span>);
    <span class='keyword'>return</span> firstTerm( aSeed ) + aInt;
  }

  <span class='comment'>/**
  * longs.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>int</span> hash( <span class='keyword'>int</span> aSeed , <span class='keyword'>long</span> aLong ) {
    System.out.println(<span class='literal'>"long..."</span>);
    <span class='keyword'>return</span> firstTerm(aSeed)  + (<span class='keyword'>int</span>)( aLong ^ (aLong &gt;&gt;&gt; <span class='literal'>32</span>) );
  }

  <span class='comment'>/**
  * floats.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>int</span> hash( <span class='keyword'>int</span> aSeed , <span class='keyword'>float</span> aFloat ) {
    <span class='keyword'>return</span> hash( aSeed, Float.floatToIntBits(aFloat) );
  }

  <span class='comment'>/**
  * doubles.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>int</span> hash( <span class='keyword'>int</span> aSeed , <span class='keyword'>double</span> aDouble ) {
    <span class='keyword'>return</span> hash( aSeed, Double.doubleToLongBits(aDouble) );
  }

  <span class='comment'>/**
  * &lt;code&gt;aObject&lt;/code&gt; is a possibly-null object field, and possibly an array.
  *
  * If &lt;code&gt;aObject&lt;/code&gt; is an array, then each element may be a primitive
  * or a possibly-null object.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>int</span> hash( <span class='keyword'>int</span> aSeed , Object aObject ) {
    <span class='keyword'>int</span> result = aSeed;
    <span class='keyword'>if</span> ( aObject == <span class='keyword'>null</span>) {
      result = hash(result, <span class='literal'>0</span>);
    }
    <span class='keyword'>else</span> <span class='keyword'>if</span> ( ! isArray(aObject) ) {
      result = hash(result, aObject.hashCode());
    }
    <span class='keyword'>else</span> {
      <span class='keyword'>int</span> length = Array.getLength(aObject);
      <span class='keyword'>for</span> ( <span class='keyword'>int</span> idx = <span class='literal'>0</span>; idx &lt; length; ++idx ) {
        Object item = Array.get(aObject, idx);
        <span class='comment'>//recursive call!
</span>        result = hash(result, item);
      }
    }
    <span class='keyword'>return</span> result;
  }


  <span class='comment'>/// PRIVATE ///
</span>  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> <span class='keyword'>int</span> fODD_PRIME_NUMBER = <span class='literal'>37</span>;

  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>int</span> firstTerm( <span class='keyword'>int</span> aSeed ){
    <span class='keyword'>return</span> fODD_PRIME_NUMBER * aSeed;
  }

  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>boolean</span> isArray(Object aObject){
    <span class='keyword'>return</span> aObject.getClass().isArray();
  }
} 
</PRE>
<br>
<br>Here is an example of its use. When debugging statements are uncommented
in <tt>HashCodeUtil</tt>, the reuse of the <tt>boolean</tt>, <tt>char</tt>,
<tt>int</tt>
and <tt>long</tt> versions of <tt>hash</tt> is demonstrated :
<br>&nbsp;
<p><tt>boolean...</tt>
<br><tt>char...</tt>
<br><tt>int...</tt>
<br><tt>long...</tt>
<br><tt>long...</tt>
<br><tt>int...</tt>
<br><tt>int...</tt>
<br><tt>int...</tt>
<br><tt>int...</tt>
<br><tt>int...</tt>
<br><tt>hashCode value: -608077094</tt>
<br>
<PRE>

<span class='keyword'>import</span> java.util.*;

<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> ApartmentBuilding {

  <span class='keyword'>public</span> ApartmentBuilding (
    <span class='keyword'>boolean</span> aIsDecrepit,
    <span class='keyword'>char</span> aRating,
    <span class='keyword'>int</span> aNumApartments,
    <span class='keyword'>long</span> aNumTenants,
    <span class='keyword'>double</span> aPowerUsage,
    <span class='keyword'>float</span> aWaterUsage,
    <span class='keyword'>byte</span> aNumFloors,
    String aName,
    List aOptions,
    Date[] aMaintenanceChecks
  ){
    fIsDecrepit = aIsDecrepit;
    fRating = aRating;
    fNumApartments = aNumApartments;
    fNumTenants = aNumTenants;
    fPowerUsage = aPowerUsage;
    fWaterUsage = aWaterUsage;
    fNumFloors = aNumFloors;
    fName = aName;
    fOptions = aOptions;
    fMaintenanceChecks = aMaintenanceChecks;
  }

  <span class='keyword'>@Override</span> <span class='keyword'>public</span> <span class='keyword'>boolean</span> equals(Object that) {
    <span class='keyword'>if</span> ( <span class='keyword'>this</span> == that ) <span class='keyword'>return</span> <span class='keyword'>true</span>;
    <span class='keyword'>if</span> ( !(that <span class='keyword'>instanceof</span> ApartmentBuilding) ) <span class='keyword'>return</span> <span class='keyword'>false</span>;
    ApartmentBuilding thatBuilding = (ApartmentBuilding)that;
    <span class='keyword'>return</span> hasEqualState(thatBuilding);
  }

  <span class='keyword'>@Override</span> <span class='keyword'>public</span> <span class='keyword'>int</span> hashCode() {
    <span class='comment'>//this style of lazy initialization is 
</span>    <span class='comment'>//suitable only if the object is immutable
</span>    <span class='keyword'>if</span> ( fHashCode == <span class='literal'>0</span>) {
      <span class='keyword'>int</span> result = HashCodeUtil.SEED;
      result = HashCodeUtil.hash( result, fIsDecrepit );
      result = HashCodeUtil.hash( result, fRating );
      result = HashCodeUtil.hash( result, fNumApartments );
      result = HashCodeUtil.hash( result, fNumTenants );
      result = HashCodeUtil.hash( result, fPowerUsage );
      result = HashCodeUtil.hash( result, fWaterUsage );
      result = HashCodeUtil.hash( result, fNumFloors );
      result = HashCodeUtil.hash( result, fName );
      result = HashCodeUtil.hash( result, fOptions );
      result = HashCodeUtil.hash( result, fMaintenanceChecks );
      fHashCode = result;
    }
    <span class='keyword'>return</span> fHashCode;
  }

  <span class='comment'>//..other methods elided
</span>
  <span class='comment'>// PRIVATE ////
</span>
  <span class='comment'>/**
  * The following fields are chosen to exercise most of the different
  * cases.
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>boolean</span> fIsDecrepit;
  <span class='keyword'>private</span> <span class='keyword'>char</span> fRating;
  <span class='keyword'>private</span> <span class='keyword'>int</span> fNumApartments;
  <span class='keyword'>private</span> <span class='keyword'>long</span> fNumTenants;
  <span class='keyword'>private</span> <span class='keyword'>double</span> fPowerUsage;
  <span class='keyword'>private</span> <span class='keyword'>float</span> fWaterUsage;
  <span class='keyword'>private</span> <span class='keyword'>byte</span> fNumFloors;
  <span class='keyword'>private</span> String fName; <span class='comment'>//possibly null, say
</span>  <span class='keyword'>private</span> List fOptions; <span class='comment'>//never null
</span>  <span class='keyword'>private</span> Date[] fMaintenanceChecks; <span class='comment'>//never null
</span>  <span class='keyword'>private</span> <span class='keyword'>int</span> fHashCode;

  <span class='comment'>/**
  * Here, for two ApartmentBuildings to be equal, all fields must be equal.
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>boolean</span> hasEqualState( ApartmentBuilding that ) {
    <span class='comment'>//note the different treatment for possibly-null fields
</span>    <span class='keyword'>return</span>
      ( <span class='keyword'>this</span>.fName==<span class='keyword'>null</span> ? that.fName==<span class='keyword'>null</span> : <span class='keyword'>this</span>.fName.equals(that.fName) ) &amp;&amp;
      ( <span class='keyword'>this</span>.fIsDecrepit == that.fIsDecrepit )&amp;&amp;
      ( <span class='keyword'>this</span>.fRating == that.fRating )&amp;&amp;
      ( <span class='keyword'>this</span>.fNumApartments == that.fNumApartments ) &amp;&amp;
      ( <span class='keyword'>this</span>.fNumTenants == that.fNumTenants ) &amp;&amp;
      ( <span class='keyword'>this</span>.fPowerUsage == that.fPowerUsage ) &amp;&amp;
      ( <span class='keyword'>this</span>.fWaterUsage ==  that.fWaterUsage ) &amp;&amp;
      ( <span class='keyword'>this</span>.fNumFloors == that.fNumFloors ) &amp;&amp;
      ( <span class='keyword'>this</span>.fOptions.equals(that.fOptions) )&amp;&amp;
      ( Arrays.equals(<span class='keyword'>this</span>.fMaintenanceChecks, that.fMaintenanceChecks) );
  }

  <span class='comment'>/**
  * Exercise hashcode.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> main (String [] aArguments) {
    List options = <span class='keyword'>new</span> ArrayList();
    options.add(<span class='literal'>"pool"</span>);
    Date[] maintenanceDates = <span class='keyword'>new</span> Date[<span class='literal'>1</span>];
    maintenanceDates[<span class='literal'>0</span>] = <span class='keyword'>new</span> Date();
    <span class='keyword'>byte</span> numFloors = <span class='literal'>8</span>;

    ApartmentBuilding building = <span class='keyword'>new</span> ApartmentBuilding (
      <span class='keyword'>false</span>,
      <span class='literal'>'B'</span>,
      <span class='literal'>12</span>,
      <span class='literal'>396L</span>,
      <span class='literal'>5.2</span>,
      <span class='literal'>6.3f</span>,
      numFloors,
      <span class='literal'>"Palisades"</span>,
      options,
      maintenanceDates
    );

    System.out.println(<span class='literal'>"hashCode value: "</span> + building.hashCode());
  }
} 
</PRE>
<br>
<p><b>Example 2</b>
<P>The WEB4J tool defines a utility class for implementing <tt>hashCode</tt>. Here is an example of a 
Model Object implemented with that utility. 

<P>Items to note :
<ul>
<li>the <tt>hashCode</tt> value is calculated only once, and only if it is needed. This is only possible since this is 
an <a href='TopicActiond838-2.html'>immutable object</a>.
<li>calling the <tt>getSignificantFields()</tt> method ensures <tt>hashCode</tt> and <tt>equals</tt> 
remain 'in sync'  
</ul>
<br>
<PRE>

<span class='keyword'>package</span> hirondelle.fish.main.discussion; 

<span class='keyword'>import</span> java.util.*;
<span class='keyword'>import</span> hirondelle.web4j.model.ModelCtorException;
<span class='keyword'>import</span> hirondelle.web4j.model.ModelUtil;
<span class='keyword'>import</span> hirondelle.web4j.model.Check;
<span class='keyword'>import</span> hirondelle.web4j.security.SafeText;
<span class='keyword'>import</span> <span class='keyword'>static</span> hirondelle.web4j.util.Consts.FAILS;

<span class='comment'>/** 
 Comment posted by a possibly-anonymous user.
*/</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> Comment { 

  <span class='comment'>/**
   Constructor. 
     
   @param aUserName identifies the logged in user posting the comment. 
   @param aBody the comment, must have content.
   @param aDate date and time when the message was posted.
  */</span>
  <span class='keyword'>public</span> Comment (
    SafeText aUserName, SafeText aBody, Date aDate
  ) <span class='keyword'>throws</span> ModelCtorException {
    fUserName = aUserName;
    fBody = aBody;
    fDate = aDate.getTime();
    validateState();
  }

  <span class='comment'>/** Return the logged in user name passed to the constructor. */</span>
  <span class='keyword'>public</span> SafeText getUserName() {
    <span class='keyword'>return</span> fUserName;
  }

  <span class='comment'>/** Return the body of the message passed to the constructor.  */</span>
  <span class='keyword'>public</span> SafeText getBody() {
    <span class='keyword'>return</span> fBody;
  }

  <span class='comment'>/**
   Return a &lt;a href="http://www.javapractices.com/Topic15.cjp"&gt;defensive copy&lt;/a&gt; 
   of the date passed to the constructor.
   
   &lt;P&gt;The caller may change the state of the returned value, without affecting 
   the internals of this &lt;tt&gt;Comment&lt;/tt&gt;. Such copying is needed since 
   a {@link Date} is a mutable object.
  */</span>
  <span class='keyword'>public</span> Date getDate() {
    <span class='comment'>// the returned object is independent of fDate
</span>    <span class='keyword'>return</span> <span class='keyword'>new</span> Date(fDate);
  }

  <span class='comment'>/** Intended for debugging only. */</span>
  <span class='keyword'>@Override</span> <span class='keyword'>public</span> String toString() {
    <span class='keyword'>return</span> ModelUtil.toStringFor(<span class='keyword'>this</span>);
  }

  <span class='keyword'>@Override</span> <span class='keyword'>public</span> <span class='keyword'>boolean</span> equals( Object aThat ) {
    Boolean result = ModelUtil.quickEquals(<span class='keyword'>this</span>, aThat);
    <span class='keyword'>if</span> ( result == <span class='keyword'>null</span> ){
      Comment that = (Comment) aThat;
      result = ModelUtil.equalsFor(
        <span class='keyword'>this</span>.getSignificantFields(), that.getSignificantFields()
      );
    }
    <span class='keyword'>return</span> result;    
  }

  <span class='keyword'>@Override</span> <span class='keyword'>public</span> <span class='keyword'>int</span> hashCode() {
    <span class='keyword'>if</span> ( fHashCode == <span class='literal'>0</span> ) {
      fHashCode = ModelUtil.hashCodeFor(getSignificantFields());
    }
    <span class='keyword'>return</span> fHashCode;
  }

  <span class='comment'>// PRIVATE // 
</span>  <span class='keyword'>private</span> <span class='keyword'>final</span> SafeText fUserName;
  <span class='keyword'>private</span> <span class='keyword'>final</span> SafeText fBody;
  <span class='comment'>/** Long is used here instead of Date in order to ensure immutability.*/</span>
  <span class='keyword'>private</span> <span class='keyword'>final</span> <span class='keyword'>long</span> fDate;
  <span class='keyword'>private</span> <span class='keyword'>int</span> fHashCode;
  
  <span class='keyword'>private</span> Object[] getSignificantFields(){
    <span class='keyword'>return</span> <span class='keyword'>new</span> Object[] {fUserName, fBody, <span class='keyword'>new</span> Date(fDate)};
  }
  
  <span class='keyword'>private</span> <span class='keyword'>void</span> validateState() <span class='keyword'>throws</span> ModelCtorException {
    ModelCtorException ex = <span class='keyword'>new</span> ModelCtorException();
    <span class='keyword'>if</span>( FAILS ==  Check.required(fUserName) ) {
      ex.add(<span class='literal'>"User name must have content."</span>);
    }
    <span class='keyword'>if</span> ( FAILS == Check.required(fBody) ) {
      ex.add(<span class='literal'>"Comment body must have content."</span>);
    }
    <span class='keyword'>if</span> ( ! ex.isEmpty() ) <span class='keyword'>throw</span> ex;
  }
}
 
</PRE>
<br>
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicAction1deb-2.html?Id=17'>Implementing equals</a> <br>
 
  
  <a href='TopicActiond838-2.html?Id=29'>Immutable objects</a> <br>
 
  
  <a href='TopicAction88f9-2.html?Id=34'>Lazy initialization</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='28'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=28 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:36 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
